package com.guan.oss.service.impl;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.model.PutObjectRequest;
import com.aliyun.oss.model.PutObjectResult;
import com.guan.oss.service.OssService;
import com.guan.oss.utils.ConstandPropertiesUtils;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Service
public class OssServiceImpl implements OssService {

    /** 上传文件-头像
     *
     * @param file
     * @return
     */
    @Override
    public String uploadFileAvatar(MultipartFile file) {

        /**
         * 通过工具类获取值
         */
        // 地域节点
        String endpoint = ConstandPropertiesUtils.END_POINT;
        // 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
        String accessKeyId = ConstandPropertiesUtils.KEY_ID;
        String accessKeySecret = ConstandPropertiesUtils.KEY_SECRET;
        // 填写Bucket名称，例如examplebucket。
        String bucketName = ConstandPropertiesUtils.BUCKET_NAME;

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {

            //获取上传文件输入流
            InputStream inputStream = file.getInputStream();
            //获取文件名称
            String originalFilename = file.getOriginalFilename();
            //随机唯一值
            String uuid = UUID.randomUUID().toString().replaceAll("-", "");
            //拼接随机唯一值
            originalFilename = uuid+originalFilename;
            //文件按照日期分类 2022/12/30/01.jpg 获取当前日期
            String datePath = new DateTime().toString("yyyy/MM/dd");
            originalFilename = datePath+"/"+originalFilename;
            // 上传文件。
            ossClient.putObject(bucketName,originalFilename,inputStream);
            // https://my-bucket-edu.oss-cn-beijing.aliyuncs.com/pic%20%281%29.png 根据oss路径规则 拼接url
            String url = "https://"+bucketName+"."+endpoint+"/"+originalFilename;
            return url;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }
}
